<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import VerifyCodeImage from './component/verifyCodeImage.vue'
import { useUserStore } from '@/stores/modules/user'
import { encryptHex, decryptHex } from '../../utils/aesUtil'
import { ElMessage } from 'element-plus'
import Cookies from 'js-cookie'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const loginForm = ref({
  phone: '',
  password: '',
  verifyCode: '',
  rememberMe: false
})

const formErrors = reactive({
  phone: '',
  password: '',
  verifyCode: ''
})

const verifyCodeRef = ref(null)
const currentVerifyCode = ref('')

// Cookie 相关常量
const COOKIE_KEYS = {
  PHONE: 'login_phone',
  PASSWORD: 'login_password',
  REMEMBER_ME: 'login_remember_me'
}

// 保存登录信息到 Cookie
const saveLoginInfo = () => {
  if (loginForm.value.rememberMe) {
    // 加密密码后保存
    const encryptedPassword = encryptHex(loginForm.value.password)
    Cookies.set(COOKIE_KEYS.PHONE, loginForm.value.phone, { expires: 30 })
    Cookies.set(COOKIE_KEYS.PASSWORD, encryptedPassword, { expires: 30 })
    Cookies.set(COOKIE_KEYS.REMEMBER_ME, 'true', { expires: 30 })
  } else {
    // 清除 Cookie
    Cookies.remove(COOKIE_KEYS.PHONE)
    Cookies.remove(COOKIE_KEYS.PASSWORD)
    Cookies.remove(COOKIE_KEYS.REMEMBER_ME)
  }
}

// 从 Cookie 读取登录信息
const loadLoginInfo = () => {
  const rememberMe = Cookies.get(COOKIE_KEYS.REMEMBER_ME)
  if (rememberMe === 'true') {
    const savedPhone = Cookies.get(COOKIE_KEYS.PHONE)
    const savedPassword = Cookies.get(COOKIE_KEYS.PASSWORD)
    
    if (savedPhone && savedPassword) {
      try {
        // 解密密码
        const decryptedPassword = decryptHex(savedPassword)
        loginForm.value.phone = savedPhone
        loginForm.value.password = decryptedPassword
        loginForm.value.rememberMe = true
      } catch (error) {
        console.error('解密密码失败:', error)
        // 解密失败时清除相关 Cookie
        Cookies.remove(COOKIE_KEYS.PHONE)
        Cookies.remove(COOKIE_KEYS.PASSWORD)
        Cookies.remove(COOKIE_KEYS.REMEMBER_ME)
      }
    }
  }
}

// 处理记住我复选框变化
const handleRememberMeChange = () => {
  if (!loginForm.value.rememberMe) {
    // 取消勾选时清除 Cookie
    Cookies.remove(COOKIE_KEYS.PHONE)
    Cookies.remove(COOKIE_KEYS.PASSWORD)
    Cookies.remove(COOKIE_KEYS.REMEMBER_ME)
  }
}

// 页面初始化时读取 Cookie
onMounted(() => {
  loadLoginInfo()
})

const handleVerifyCodeChange = (code) => {
  currentVerifyCode.value = code
}

// 手机号校验
const validatePhone = (phone) => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phone) {
    return '请输入手机号'
  }
  if (!phoneRegex.test(phone)) {
    return '请输入正确的手机号格式'
  }
  return ''
}

// 密码校验
const validatePassword = (password) => {
  if (!password) {
    return '请输入密码'
  }
  if (password.length < 6 || password.length > 20) {
    return '密码长度应为6-20位'
  }
  return ''
}

// 验证码校验
const validateVerifyCode = (verifyCode) => {
  if (!verifyCode) {
    return '请输入验证码'
  }
  return ''
}

// 验证码正确性校验
const validateVerifyCodeCorrectness = (verifyCode) => {
  if (!verifyCode) {
    return '请输入验证码'
  }
  if (verifyCode.toLowerCase() !== currentVerifyCode.value.toLowerCase()) {
    return '验证码错误'
  }
  return ''
}

// 实时校验
const validateField = (field, value) => {
  switch (field) {
    case 'phone':
      formErrors.phone = validatePhone(value)
      break
    case 'password':
      formErrors.password = validatePassword(value)
      break
    case 'verifyCode':
      formErrors.verifyCode = validateVerifyCode(value)
      break
  }
}

// 清除错误信息
const clearError = (field) => {
  formErrors[field] = ''
}

// 整体表单校验
const validateForm = () => {
  const phoneError = validatePhone(loginForm.value.phone)
  const passwordError = validatePassword(loginForm.value.password)
  const verifyCodeError = validateVerifyCodeCorrectness(loginForm.value.verifyCode)

  formErrors.phone = phoneError
  formErrors.password = passwordError
  formErrors.verifyCode = verifyCodeError

  return !phoneError && !passwordError && !verifyCodeError
}

const handleLogin = async () => {
  // 整体表单校验
  if (!validateForm()) {
    return
  }

  // 验证码错误时自动刷新
  if (formErrors.verifyCode) {
    verifyCodeRef.value?.handleLoginFailed()
    loginForm.value.verifyCode = ''
  }

  // 加密密码并调用登录
  const encryptedPassword = encryptHex(loginForm.value.password)
  try {
    await userStore.loginAction({
      phone: loginForm.value.phone,
      password: encryptedPassword
    })
    
    // 登录成功后保存登录信息
    saveLoginInfo()
    await userStore.getUserInfoAction()
    ElMessage.success('登录成功')
    
    // 获取redirectUrl参数，如果有则跳转到指定页面，否则跳转到默认页面
    const redirectUrl = route.query.redirectUrl
    if (redirectUrl) {
      router.push(redirectUrl)
    } else {
      router.push('/user')
    }
  } catch (error) {
    console.log("登录失败" ,error);
    
    // 登录失败时刷新验证码并清空输入框
    verifyCodeRef.value?.handleLoginFailed()
    loginForm.value.verifyCode = ''
  }
}

</script>

<template>
  <div class="login-container">
    <form class="form" @submit.prevent="handleLogin">
      <div class="logo-container">
        <img src="@/assets/logo/logo.png" alt="logo" class="logo">
      </div>
      
      <div class="flex-column">
        <label>手机号</label>
      </div>
      <div class="input-wrapper">
        <div class="inputForm" :class="{ 'error': formErrors.phone }">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M17 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2z"/>
            <line x1="12" y1="18" x2="12.01" y2="18"/>
          </svg>
          <input 
            placeholder="请输入手机号" 
            class="input" 
            type="text"
            v-model="loginForm.phone"
            @input="validateField('phone', loginForm.phone)"
            @blur="validateField('phone', loginForm.phone)"
            @focus="clearError('phone')"
          >
        </div>
        <div v-if="formErrors.phone" class="error-message">{{ formErrors.phone }}</div>
      </div>

      <div class="flex-column">
        <label>密码</label>
      </div>
      <div class="input-wrapper">
        <div class="inputForm" :class="{ 'error': formErrors.password }">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" viewBox="-64 0 512 512" height="20">
            <path d="m336 512h-288c-26.453125 0-48-21.523438-48-48v-224c0-26.476562 21.546875-48 48-48h288c26.453125 0 48 21.523438 48 48v224c0 26.476562-21.546875 48-48 48zm-288-288c-8.8125 0-16 7.167969-16 16v224c0 8.832031 7.1875 16 16 16h288c8.8125 0 16-7.167969 16-16v-224c0-8.832031-7.1875-16-16-16zm0 0"></path>
            <path d="m304 224c-8.832031 0-16-7.167969-16-16v-80c0-52.929688-43.070312-96-96-96s-96 43.070312-96 96v80c0 8.832031-7.167969 16-16 16s-16-7.167969-16-16v-80c0-70.59375 57.40625-128 128-128s128 57.40625 128 128v80c0 8.832031-7.167969 16-16 16zm0 0"></path>
          </svg>        
          <input 
            placeholder="请输入密码" 
            class="input" 
            type="password"
            v-model="loginForm.password"
            @input="validateField('password', loginForm.password)"
            @blur="validateField('password', loginForm.password)"
            @focus="clearError('password')"
            autocomplete="current-password"
          >
        </div>
        <div v-if="formErrors.password" class="error-message">{{ formErrors.password }}</div>
      </div>

      <div class="flex-column">
        <label>验证码</label>
      </div>
      <div class="verify-code-wrapper">
        <div class="verify-code-row">
          <div class="inputForm verify-code-input" :class="{ 'error': formErrors.verifyCode }">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
              <circle cx="12" cy="16" r="1"/>
              <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
            </svg>
            <input 
              placeholder="请输入验证码" 
              class="input" 
              type="text"
              v-model="loginForm.verifyCode"
              maxlength="4"
              @input="validateField('verifyCode', loginForm.verifyCode)"
              @blur="validateField('verifyCode', loginForm.verifyCode)"
              @focus="clearError('verifyCode')"
            >
          </div>
          <VerifyCodeImage 
            ref="verifyCodeRef"
            :width="120"
            :height="50"
            :length="4"
            @code-change="handleVerifyCodeChange"
          />
        </div>
        <div v-if="formErrors.verifyCode" class="error-message">{{ formErrors.verifyCode }}</div>
      </div>

      <div class="flex-row">
        <div class="remember-me">
          <input type="checkbox" v-model="loginForm.rememberMe" id="rememberMe" @change="handleRememberMeChange">
          <label for="rememberMe">记住我</label>
        </div>
      </div>
      
      <button class="button-submit" type="submit">登录</button>
      
      <p class="p notice">本系统未提供注册服务，请联系管理员添加账号</p>
    </form>
  </div>
</template>

<style scoped>
  .login-container {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  }

  .form {
    display: flex;
    flex-direction: column;
    gap: 10px;
    background-color: #ffffff;
    padding: 30px;
    width: 450px;
    border-radius: 20px;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  }

  .logo-container {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 20px;
  }

  .logo {
    width: 100px;
    height: 100px;
    object-fit: contain;
    border-radius: 50%;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  ::placeholder {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  }

  .form button {
    align-self: flex-end;
  }

  .flex-column > label {
    color: #151717;
    font-weight: 600;
  }

  .inputForm {
    border: 1.5px solid #ecedec;
    border-radius: 10px;
    height: 50px;
    display: flex;
    align-items: center;
    padding-left: 10px;
    transition: 0.2s ease-in-out;
  }

  .input {
    margin-left: 10px;
    border-radius: 10px;
    border: none;
    width: 100%;
    height: 100%;
  }

  .input:focus {
    outline: none;
  }

  .inputForm:focus-within {
    border: 1.5px solid #2d79f3;
  }

  .flex-row {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 10px;
    justify-content: space-between;
  }

  .flex-row > div > label {
    font-size: 14px;
    color: black;
    font-weight: 400;
  }

  .remember-me {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .remember-me input[type="checkbox"] {
    margin: 0;
    width: 16px;
    height: 16px;
  }

  .notice {
    color: #666;
    font-size: 12px;
    text-align: center;
    margin-top: 15px;
  }

  .verify-code-row {
    display: flex;
    gap: 10px;
    align-items: flex-end;
  }

  .verify-code-input {
    flex: 1;
  }

  .inputForm.error {
    border-color: #f56c6c;
  }

  .input-wrapper {
    position: relative;
    margin-bottom: 10px;
  }

  .verify-code-wrapper {
    position: relative;
    margin-bottom: 10px;
  }

  .error-message {
    position: absolute;
    top: 100%;
    left: 0;
    color: #f56c6c;
    font-size: 12px;
    margin-top: 2px;
    line-height: 1.2;
    z-index: 1;
  }

  .span {
    font-size: 14px;
    margin-left: 5px;
    color: #2d79f3;
    font-weight: 500;
    cursor: pointer;
  }

  .button-submit {
    margin: 20px 0 10px 0;
    background-color: #151717;
    border: none;
    color: white;
    font-size: 15px;
    font-weight: 500;
    border-radius: 10px;
    height: 50px;
    width: 100%;
    cursor: pointer;
  }

  .p {
    text-align: center;
    color: black;
    font-size: 14px;
    margin: 5px 0;
  }

  .btn {
    margin-top: 10px;
    width: 100%;
    height: 50px;
    border-radius: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: 500;
    gap: 10px;
    border: 1px solid #ededef;
    background-color: white;
    cursor: pointer;
    transition: 0.2s ease-in-out;
  }

  .btn:hover {
    border: 1px solid #2d79f3;
  }
</style>